
var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

layer.ready(function () {
    //获取所有客户信息
    $.ajax({
        url:"otherOutStock/add/getCustomerAllInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //客户名称
                    $('#customerCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });
});

let initData = [];
table.render({
    elem: '#mains'
    ,data:initData
    ,url:'carryDetail/importCarryPlanByPage'
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'carryPlanNo', title:'出运编号',sort:true}
        ,{field:'saleContractNo', title:'合同编号',sort:true}
        ,{field:'customerContractNo', title:'客户合同号',sort:true}
        ,{field:'customerName', title:'客户名称',sort:true}
        ,{field:'signingDate', title:'签约日期',sort:true}
        ,{field:'deliveryDate', title:'货好日期',sort:true}
        ,{field:'carryDate', title:'出运日期',sort:true}
        ,{field:'modeOfTransport', title:'运输方式',sort:true}
        ,{field:'salesmanName', title:'业务员',sort:true}
        ,{field:'businessModelName', title:'业务模式',sort:true,templet: function(data){
                let rmbRate = getBusinessModel(data.businessModelName);
                return rmbRate;
            }}
    ]]
    ,id: 'mainstableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,url:"carryDetail/import/getCarryPlanProduct"
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field:'productCode', title:'产品编码', sort : true}
                ,{field:'specNo', title:'规格编码', sort : true}
                ,{field:'productSpecExplanation', title:'规格说明', sort : true}
                ,{field:'productCname', title:'中文名称', sort : true}
                ,{field:'productEname', title:'英文名称', sort : true}
                ,{field:'productCdesc', title: '中文描述', sort: true}
                ,{field:'productEdesc', title: '英文描述', sort: true}
                ,{field:'productNum', title:'数量', sort : true}
                ,{field:'productUnitName', title:'单位', sort : true}
                ,{field:'remainingQuantity', title:'剩余数量', sort : true}
                ,{field:'fcUnitPrice', title: '单价', sort : true}
                ,{field:'moneySubtotal', width: 120, title: '金额小计', sort : true}
            ]]
            ,id: 'producttableid'
            ,where: {
                id:res.data.length == 0 ? "":res.data[0].id //默认第一条信息，数据为空则id为空
            }
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });
    }
});

//监听主表复选框
table.on('checkbox(mainstable)', function (data) {
    let id = data.data.id;
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
                id:id
            }
        ,done: function (res, curr, count) {
            let child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){
                for(var i = 0; i < res.data.length; i++){
                    changeList.push(res.data[i]);
                }
            }else{
                if(changeList.length > 0){
                    for(var i = 0; i < res.data.length; i++){
                        deleteData(res.data[i]);
                    }
                }
            }
            form.render('checkbox');

            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
});

function getBusinessModel(code){
    let name = "";
    //获取业务模式信息
    $.ajax({
        url:"offer/getBusinessModel",
        async:false,
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    if(code == data.data[i].code){
                        name = data.data[i].name;
                        break;
                    }
                }
            }
        }
    });
    return name;
}


function deleteData(data){
    let id = data.id;
    let parentId = data.parentId;
    for(var j = 0; j < changeList.length; j++){
        if (changeList[j].id == id && changeList[j].parentId == parentId) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}


//监听子复选框
table.on('checkbox(producttable)', function (obj) {
    if (obj.checked) {
        changeList.push(obj.data);
    } else {
        for (let index in changeList) {
            if (changeList[index].id == obj.data.id && changeList[index].parentId == obj.data.parentId) {
                changeList.splice(index,1);
            }
        }
    }
    form.render('checkbox');
});

//单击行事件
table.on('row(mainstable)', function (obj) {
    let id = obj.data.id;
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].id == res.data[i].id &&  changeList[j].parentId == res.data[i].parentId) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
        done: function (res, curr, count) {
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
});

form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        //防止重复提交问题
        preventDuplicateSubmissions();
        //产品明细数据
        let oldData =  parent.table.cache["storageproductstableid"];
        //费用数据
        let oldCostData = parent.table.cache["costtableid"];
        //附件数据
        let oldAnnexData = parent.table.cache["attachmenttableid"];
        let tempCost = [];
        let tempAnnex = [];
        $.each(changeList, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i]["sameId"] != "undefined" && oldData[i]["sameId"] == changeList[index].id;
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //不存在重复数据,添加数据
                //1.产品
                let tempData = changeList[index];
                tempData["tempId"] = GenNonDuplicateID(3) + (index+1)
                tempData["sameId"] = tempData.id;
                tempData["id"] = null;
                oldData.push(tempData);

                //2.费用
                let costList = tempData.costList;
                for(let i in costList){
                    tempCost.push(costList[i]);
                }

                //3.附件
                let annexList = tempData.annexList;
                for(let i in annexList){
                    tempAnnex.push(annexList[i]);
                }

                //4.配件
                let partsList = tempData.partsList;
                for(let i in partsList){
                    partsList[i]["tempId"] = GenNonDuplicateID(3) + (i+1)
                }
            }

        });

        //剔除重复费用
        let newCostData = deleteObject(tempCost);
        let newTempCost = [];
        for(let i in newCostData){
            let flag = true;
            for(let j in oldCostData){
                if(newCostData[i].id == oldCostData[j].tempId){
                    flag = false;
                    break;
                }
            }
            if(flag){
                //不存在重复费用数据,新增
                newCostData[i]["tempId"] = newCostData[i].id;
                newCostData[i].id = null;
                newTempCost.push(newCostData[i]);
            }
        }
        oldCostData.push.apply(oldCostData, newTempCost);

        //剔除重复附件
        let newAnnexData = deleteObject(tempAnnex);
        let newTempAnnex = [];
        for(let i in newAnnexData){
            let flag = true;
            let annexId = newAnnexData[i]["id"];
            for(let j in oldAnnexData){
                if(annexId == oldAnnexData[j].id){
                    flag = false;
                    break;
                }
            }
            if(flag){
                //不存在重复附件数据,新增
                newTempAnnex.push(newAnnexData[i]);
            }
        }
        oldAnnexData.push.apply(oldAnnexData, newTempAnnex);

        //重载产品明细表单
        parent.table.reload('storageproductstableid', {data:oldData, limit:oldData.length});

        //重载费用明细表单
        parent.table.reload('costtableid', {data:oldCostData, limit:oldCostData.length});

        //重载附件表单
        parent.table.reload('attachmenttableid', {data:oldAnnexData});

        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        })
    }
})


$("#shutdown").on("click",function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}
//删除数组对象中重复对象
function deleteObject(obj) {
    let uniques = [];
    let stringify = {};
    for (let i = 0; i < obj.length; i++) {
        let keys = Object.keys(obj[i]);
        keys.sort(function(a, b) {
            return (Number(a) - Number(b));
        });
        let str = '';
        for (let j = 0; j < keys.length; j++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if (!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str] = true;
        }
    }
    uniques = uniques;
    return uniques;
}